package wang.aweb.childcar.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wang.aweb.childcar.exception.CarException;
import wang.aweb.childcar.exception.CarExceptionEnum;
import wang.aweb.childcar.model.dao.AgentMapper;
import wang.aweb.childcar.model.dao.DeviceMapper;
import wang.aweb.childcar.model.pojo.Agent;
import wang.aweb.childcar.model.pojo.Device;
import wang.aweb.childcar.model.query.AgentParam;
import wang.aweb.childcar.model.req.AddAgentReq;
import wang.aweb.childcar.model.req.UpdateAgentReq;
import wang.aweb.childcar.model.vo.AgentVO;
import wang.aweb.childcar.service.AgentService;
import wang.aweb.childcar.service.ComrateLogService;
import wang.aweb.childcar.service.DeviceService;
import wang.aweb.childcar.util.Md5Utils;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AgentServiceImpl implements AgentService {
    @Autowired
    private ComrateLogService comrateLogService;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private DeviceService deviceService;
    @Override
    public List<Agent> getAll(){
        List<Agent> agents=agentMapper.selectAll();
        return agents;
    }
    @Override
    public void update(Agent updateAgentReq){
        String username=updateAgentReq.getUsername();
        Agent oldAgent=agentMapper.selectByUsername(username);
        if(oldAgent!=null && !oldAgent.getId().equals(updateAgentReq.getId())){
            throw new CarException(CarExceptionEnum.NAME_EXIST);
        }

        int count=agentMapper.updateByPrimaryKeySelective(updateAgentReq);
        if(count==0){
            throw new CarException(CarExceptionEnum.UPDATE_FAILED);
        }

    }
    @Override
    public void disableOrEnable(Integer id){
        Agent agent=agentMapper.selectByPrimaryKey(id);
        if(agent.getStatus()==0){
            agent.setStatus(1);
        }else{
            agent.setStatus(0);
        }
        agentMapper.updateByPrimaryKeySelective(agent);
    }

    /**
     * 代理商结算
     * @param id 代理商ID
     * @param money 金额
     */
    @Override
    public void jiesuan(Integer id, Float money){
        Integer mo=Math.round(money*100);
        Agent currentAgent=agentMapper.selectByPrimaryKey(id);
        if(currentAgent.getMoney()<mo){
            throw new CarException(CarExceptionEnum.MONEY_NOT_ENOTH);
        }
        agentMapper.updateMoneyById(id,0-mo);
        comrateLogService.add(mo,id,2,null);
    }
    /**
     * 通过ID删除代理商
     * @param id 代理商ID
     */
    @Override
    public void deleteAgentById(Integer id){
        List<Device> deviceList=deviceService.selectByAgentId(id);
        if(deviceList.size()>0){
            throw new CarException(CarExceptionEnum.DELETE_FAILED);
        }
        Agent agent=agentMapper.selectByPrimaryKey(id);
        if(agent==null){
            throw new CarException(CarExceptionEnum.DELETE_FAILED);
        }
        int count=agentMapper.deleteByPrimaryKey(id);
        if(count==0){
            throw new CarException(CarExceptionEnum.DELETE_FAILED);
        }
    }

    /**
     * 创建代理商
     * @param addAgentReq 传递参数
     * @throws NoSuchAlgorithmException
     */
    @Override
    public void create(AddAgentReq addAgentReq) throws NoSuchAlgorithmException {
        //不能重名
        String username=addAgentReq.getUsername();
        Agent oldAgent=agentMapper.selectByUsername(username);
        if(oldAgent!=null){
            throw new CarException(CarExceptionEnum.NAME_EXIST);
        }
        Agent agent=new Agent();
        agent.setPassword(Md5Utils.getMD5Str("123456"));
        agent.setMoney(0);
        agent.setComrate(addAgentReq.getComrate());
        agent.setUsername(addAgentReq.getUsername());
        agent.setMobilePhone(addAgentReq.getMobile_phone());
        agent.setCreateTime(new Date());
        agent.setPid(addAgentReq.getPid());
        agent.setDonateEnable(0);
        agent.setStatus(1);
        agent.setInputtime(String.valueOf(new Date().getTime()/100));
        agentMapper.insert(agent);
    }
    @Override
    public PageInfo getList(Integer page, Integer limit, AgentParam agentParam){
        PageHelper.startPage(page,limit);
        List<Agent> agentList=agentMapper.selectList(agentParam);

        List<AgentVO> agentVOList=agentListToAgentVOList(agentList);
        PageInfo orderPageInfo=new PageInfo<>(agentList);
        orderPageInfo.setList(agentVOList);
        return orderPageInfo;
    }
    private List<AgentVO> agentListToAgentVOList(List<Agent> agentList){
        List<AgentVO> agentVOList=new ArrayList<>();
        for (int i = 0; i < agentList.size(); i++) {
            Agent agent =  agentList.get(i);
            agentVOList.add(getAgentVO(agent));
        }
        return agentVOList;
    }
    public AgentVO getAgentVO(Agent agent){
        if(agent==null){
            return null;
        }else{
            AgentVO agentVO=new AgentVO();
            BeanUtils.copyProperties(agent,agentVO);
            agentVO.setMoney((float)agent.getMoney()/100);
            agentVO.setCreate_time(agent.getCreateTime());
            agentVO.setMobile_phone(agent.getMobilePhone());
            return agentVO;
        }

    }
    public Agent getById(Integer agentId){
        Agent agent=agentMapper.selectByPrimaryKey(agentId);
        return agent;
    }
    @Override
    public AgentVO findVOById(Integer agentId){
        Agent agent=getById(agentId);
        return getAgentVO(agent);
    }

    @Override
    public AgentVO selectByMobile(String agentmobile) {
        Agent agent=agentMapper.selectByMobile(agentmobile);
        return getAgentVO(agent);
    }

    @Override
    public AgentVO selectByUsername(String username) {
        Agent agent=agentMapper.selectByUsername(username);
        return getAgentVO(agent);
    }

    @Override
    public void updateMoneyById(String orderNo,Integer id, Integer comrateMoney) {
        agentMapper.updateMoneyById(id,comrateMoney);
        comrateLogService.add(comrateMoney,id,1,orderNo);
    }

    @Override
    public Integer doLogin(String openid, String username, String password) {
        Agent currentAgent=agentMapper.selectLogin(username,password);
        if(currentAgent!=null){
            if(currentAgent.getOpenid()==""){
                currentAgent.setOpenid(openid);
                agentMapper.updateByPrimaryKeySelective(currentAgent);
            }
        }else{
            throw new CarException(CarExceptionEnum.AGENT_PASSWORD_ERROR);
        }
        return currentAgent.getId();
    }

}
